package com.thinklab.view3g;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.widget.Toast;

public class V3NetworkService extends Service{
	NetworkThread mV3MonitorThread = null; 
	NetworkStatusChecker mNetworkChecker;
	V3Common mCommon;
	long nRxBytes;
	long nTxBytes;
	final int mNotificationid = 16815132;
	
	public final static String USAGE_REFRESHED = "com.thinklab.view3g.usage_refreshed";
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		mCommon = V3Common.getInstance(getApplicationContext());
		nRxBytes = mCommon.get3GReceivePre();
		nTxBytes = mCommon.get3GTransmitPre();
		
		if(mCommon.Is3GConnected()){
			startThread(mCommon.get3GInterface());
		}
		
		mNetworkChecker = new NetworkStatusChecker();
		registerReceiver(mNetworkChecker, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
		updateNotification();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(mNetworkChecker);
		stopThread();
		upDatePreUsage();
		deleteNotification();
		super.onDestroy();
	}
	
	private void upDatePreUsage(){
		mCommon.set3GReceivePre(nRxBytes);
		mCommon.set3GTransmitPre(nTxBytes);		
	}
	
	public void startThread(String _interface)
	{
		if(mV3MonitorThread == null){
			mV3MonitorThread = new NetworkThread(_interface);
			mV3MonitorThread.start();
		}
	}
	
	public void stopThread()
	{
		if(mV3MonitorThread != null){
			mV3MonitorThread.interrupt();
		}
		mV3MonitorThread = null;
	}

	public class NetworkStatusChecker extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("android.net.conn.CONNECTIVITY_CHANGE")){
                NetworkInfo networkinfo = (NetworkInfo)intent.getParcelableExtra("networkInfo");
                if(networkinfo.isConnected()){
                	if(networkinfo.getTypeName().equalsIgnoreCase("mobile")){
                		if(mCommon.Is3GConnected()){
                			startThread(mCommon.get3GInterface());
                		}else{
                			Toast.makeText(getApplicationContext(), getString(R.string.fail_found), Toast.LENGTH_SHORT).show();
                		}
                	}else{
                		stopThread();
                	}
                }else{
                	stopThread();
                }
            }
		}	
	}
	public class NetworkThread extends Thread{
		String mRxPath;
		String mTxPath;
		
		public NetworkThread(String _interface){
			mRxPath = "/sys/class/net/" + _interface + "/statistics/rx_bytes";
			mTxPath = "/sys/class/net/" + _interface + "/statistics/tx_bytes";
		}
		
		@Override
		public void run() {
			super.run();
			try {
				while(true){
					long nNowRx = getlongFromFile(mRxPath);
					long nNowTx = getlongFromFile(mTxPath);
					if(nNowRx < nRxBytes || nNowTx < nTxBytes){
						nRxBytes = 0;
						nTxBytes = 0;
					}
					mCommon.add3GReceive(nNowRx - nRxBytes);
					mCommon.add3GTransmit(nNowTx - nTxBytes);
					
					if(mCommon.Is3GConnected() == false){
						stopThread();
						break;
					}
					nRxBytes = nNowRx;
					nTxBytes = nNowTx;
					V3NetworkService.this.sendBroadcast(new Intent(USAGE_REFRESHED));
					
					upDatePreUsage();
					updateNotification();
					sleep(mCommon.get3GRefreshSpeed() * 1000);
				}
			} catch (InterruptedException e) {
				
			}
		}
		public long getlongFromFile(String Path)
		{
			long ret = 0;
			try {
				FileInputStream fi = new FileInputStream(new File(Path));
				byte[] data = new byte[fi.available()];
				fi.read(data);
				for(int i=0;i<fi.available() && data[i] >= '0' && data[i] <='9';++i){
					ret = ret*10 + (data[i]-'0');
				}
			} catch (FileNotFoundException e) {
				
			} catch (IOException e) {
				
			}
			return ret;
		}
	}
	public void updateNotification(){
		NotificationManager notificationManager =
		    (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		Notification notification = new Notification(R.drawable.icon,"3G Usage Notification",System.currentTimeMillis());
		notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
		Intent intent = new Intent(this,V3Main.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this,0, intent, 0);
		StringBuilder sb = new StringBuilder();
		
		String downmb = String.format("%.1f", mCommon.get3GReceive()/1024.0/1024.0);
		String upmb = String.format("%.1f", mCommon.get3GTransmit()/1024.0/1024.0);
		
		sb.append(getString(R.string.noti_down)).append(downmb).append("MB, ");
		sb.append(getString(R.string.noti_up)).append(upmb).append("MB");
		
		notification.setLatestEventInfo(this,getString(R.string.noti_title),sb.toString(), pendingIntent);
		notificationManager.notify(mNotificationid, notification);
	}
	public void deleteNotification(){
		NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notificationManager.cancel(mNotificationid);
	}
}







